package me.xlgp.xiquzimu.ui.changduan;

import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableOnSubscribe;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Function;
import me.xlgp.xiquzimu.data.ChangCiRepository;
import me.xlgp.xiquzimu.data.ChangDuanInfoRepository;
import me.xlgp.xiquzimu.data.ChangDuanRepository;
import me.xlgp.xiquzimu.designpatterns.ObserverHelper;
import me.xlgp.xiquzimu.params.TagChangDuan;
import me.xlgp.xiquzimu.util.ChangDuanHelper;
import me.xlgp.xiquzimu.util.PinYinHelper;

public class ChangDuanViewModel extends ViewModel {

    public MutableLiveData<String> deleteState = new MutableLiveData<>();
    public MutableLiveData<String> loadState = new MutableLiveData<>();
    MutableLiveData<List<TagChangDuan>> changduanList = null;

    public MutableLiveData<List<TagChangDuan>> getChangduanList() {
        if (changduanList == null) {
            changduanList = new MutableLiveData<>();
            loadChangDuanList();
        }
        return changduanList;
    }


    public void loadChangDuanList() {
        new ChangDuanRepository().list().subscribe(changDuanList -> {
            PinYinHelper.sortByPYAndName(changDuanList);
            List<TagChangDuan> list = ChangDuanHelper.getTagChangDuan(changDuanList);
            changduanList.postValue(list);
        }, throwable -> {
            changduanList.postValue(new ArrayList<>());
            loadState.postValue("获取失败" + throwable.getMessage());
        });
    }

    public Observable<Long> fetchChangDuanList() {
        return new ChangDuanInfoRepository().fetchChangDuanList();
    }

    public void deleteChangDuanList(List<Integer> idList) {
        Observable.create((ObservableOnSubscribe<Integer>) emitter ->
                emitter.onNext(new ChangDuanRepository().deleteList(idList)))
                .map((Function<Integer, Object>) integer ->
                        new ChangCiRepository().deleteByChangDuanIdList(idList))
                .compose(ObserverHelper.transformer())
                .subscribe(new Observer<Object>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull Object o) {
                        deleteState.setValue("删除成功");
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        deleteState.setValue("删除失败");
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}
